import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const http = axios.create({
    baseURL: import.meta.env.VITE_API_URL + "/api/",
    timeout: 5000
})

http.defaults.withCredentials = true;

//添加默认请求token
http.interceptors.request.use(req => {
    let token = sessionStorage.getItem("token")
    if (token) {
        req.headers["token"] = token
    }
    return req
})

//自动解包
http.interceptors.response.use(resp => {
    //token过期自动跳转到登录页面
    if (resp.data.code === 4002) {
        ElMessage("凭证无效，请重新登录")
        sessionStorage.removeItem("token")
        sessionStorage.removeItem("isLogged")
        sessionStorage.removeItem("role")
        router.push('/login').then()
    }
    if (resp.data.code === 4003) {
        ElMessage("凭证过期，请重新登录")
        sessionStorage.removeItem("token")
        sessionStorage.removeItem("isLogged")
        sessionStorage.removeItem("role")
        router.push('/login').then()
    }
    return resp.data;
})

export default http;